/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package radiostation;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.DBManager;
import model.PlayList;
import model.Song;

/**
 *
 * @author sky
 */
public class EditListJFrame extends javax.swing.JFrame {

    /**
     * Creates new form XmlJFrame
     */
    public EditListJFrame() {
        em = DBManager.em;
        if (!em.getTransaction().isActive()) {
            em.getTransaction().begin();
        }
        initComponents();
    }

    public EditListJFrame(PlayList list) {
        em = DBManager.em;
        this.currentlist = list;
        if (!em.getTransaction().isActive()) {
            em.getTransaction().begin();
        }
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        artistOrGroupCellRenderer1 = new controller.ArtistOrGroupCellRenderer();
        timeRenderer1 = new controller.TimeRenderer();
        playList1 = currentlist;
        songQuery = em.createQuery("SELECT s FROM Song s JOIN s.playListList pl WHERE pl.playListId=:id").setParameter("id", currentlist.getPlayListId());
        songsInList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(songQuery.getResultList());
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        newJBtn = new javax.swing.JButton();
        deleteJBtn = new javax.swing.JButton();
        cancelJBtn = new javax.swing.JButton();
        saveJBtn = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jFormattedTextField1 = new javax.swing.JFormattedTextField();

        artistOrGroupCellRenderer1.setText("artistOrGroupCellRenderer1");

        timeRenderer1.setText("timeRenderer1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("RadioStation");

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/media-optical-audio.png"))); // NOI18N
        jLabel1.setText("Διαχείριση Λίστας");

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, songsInList, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${songTitle}"));
        columnBinding.setColumnName("Τίτλος");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${albumId}"));
        columnBinding.setColumnName("Συγκρότημα/Καλλιτέχνης");
        columnBinding.setColumnClass(model.Album.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${songDuration}"));
        columnBinding.setColumnName("Διάρκεια");
        columnBinding.setColumnClass(Long.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(jTable1);
        if (jTable1.getColumnModel().getColumnCount() > 0) {
            jTable1.getColumnModel().getColumn(1).setCellRenderer(artistOrGroupCellRenderer1);
            jTable1.getColumnModel().getColumn(2).setCellRenderer(timeRenderer1);
        }

        newJBtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/list-add.png"))); // NOI18N
        newJBtn.setText("Εισαγωγή");
        newJBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newJBtnActionPerformed(evt);
            }
        });

        deleteJBtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/list-remove.png"))); // NOI18N
        deleteJBtn.setText("Διαγραφή");
        deleteJBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteJBtnActionPerformed(evt);
            }
        });

        cancelJBtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/window-close.png"))); // NOI18N
        cancelJBtn.setText("Ακύρωση");
        cancelJBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelJBtnActionPerformed(evt);
            }
        });

        saveJBtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/document-save.png"))); // NOI18N
        saveJBtn.setText("Αποθήκευση");
        saveJBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveJBtnActionPerformed(evt);
            }
        });

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, playList1, org.jdesktop.beansbinding.ELProperty.create("${playListName}"), jTextField1, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jLabel2.setText("Περιγραφή");

        jLabel3.setText("Ημερομηνία");

        jFormattedTextField1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(java.text.DateFormat.getDateInstance(java.text.DateFormat.SHORT))));

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, playList1, org.jdesktop.beansbinding.ELProperty.create("${playListDate}"), jFormattedTextField1, org.jdesktop.beansbinding.BeanProperty.create("value"));
        bindingGroup.addBinding(binding);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 615, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(newJBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(deleteJBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(saveJBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelJBtn))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextField1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newJBtn)
                    .addComponent(deleteJBtn)
                    .addComponent(cancelJBtn)
                    .addComponent(saveJBtn))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void newJBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newJBtnActionPerformed
        // TODO add your handling code here:
        SelectSongJFrame ssf = new SelectSongJFrame(this);
        ssf.setVisible(true);
        thisFrame = this;
        thisFrame.setEnabled(false);
        //pat3group: Listener---------------------------------
        ssf.addWindowListener(new WindowListener() {
            @Override
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
                if (arg0 instanceof MyWindowEvent) {
                    if (((MyWindowEvent) arg0).exitAndSave) {
                        boolean songExists = false;
                        for (Song i : currentlist.getSongList()) {
                            if (newSong == i) {
                                songExists = true;
                                break;
                            }
                        }
                        if (!songExists) {
                            em.persist(newSong);
                            songsInList.add(newSong);
                            currentlist.setSongList(songsInList);
                            System.out.println("currentlist songs:"+currentlist.getSongList());
                        } else {
                            JOptionPane.showMessageDialog(thisFrame, "Το τραγούδι υπάρχει στην Λίστα", "Προσοχή", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                }
                thisFrame.setEnabled(true);
            }

            @Override
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }

            @Override
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }

            @Override
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }

            @Override
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }

            @Override
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }

            @Override
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
        //----------------------------------------------------
    }//GEN-LAST:event_newJBtnActionPerformed

    private void cancelJBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelJBtnActionPerformed
        // TODO add your handling code here:
        submit(false); //CANCEL
    }//GEN-LAST:event_cancelJBtnActionPerformed

    private void saveJBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveJBtnActionPerformed
        // pat3group: spyros - περιορισμός μισής ώρας
        long listduration=0L;
        for (Song s:songsInList) {
            listduration += s.getSongDuration();
        }
        if (listduration<MIN_DURATION) {
            long neededDuration = MIN_DURATION-listduration;
            long minutes = neededDuration/60;
            String timeStr = minutes+":"+(neededDuration - minutes*60);
            JOptionPane.showMessageDialog(thisFrame,
              "Η Λίστα πρέπει να περιέχει τραγούδια μισής ώρας τουλάχιστον.\n"
            + "Χρειάζεστε ακόμη: " + timeStr + " (ή "+ (MIN_DURATION-listduration) + " sec)", "Προσοχή", JOptionPane.ERROR_MESSAGE);
        } else {
            submit(true); //SAVE
        }
    }//GEN-LAST:event_saveJBtnActionPerformed

    private void deleteJBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteJBtnActionPerformed
        // TODO add your handling code here:
        int s = jTable1.getSelectedRow();
        if (s >= 0) {
            Song song4del = songsInList.get(jTable1.convertRowIndexToModel(s));
            //σκοτώνω μόνο τη συσχέτηση τραγουδιού λίστας 
            String qStr = "DELETE FROM RADIO.SONG_PLAY_LIST WHERE"
                        + " PLAY_LIST_ID = " + currentlist.getPlayListId()
                        + " AND SONG_ID = " + song4del.getSongId();
            em.createNativeQuery(qStr).executeUpdate();
            em.getTransaction().commit();
            em.getTransaction().begin();
            java.util.Collection data = songQuery.getResultList();
                for (Object entity : data) {
                    em.refresh(entity);
                }
                songsInList.clear();
                songsInList.addAll(data);
        }
    }//GEN-LAST:event_deleteJBtnActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EditListJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EditListJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EditListJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EditListJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new EditListJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private controller.ArtistOrGroupCellRenderer artistOrGroupCellRenderer1;
    private javax.swing.JButton cancelJBtn;
    private javax.swing.JButton deleteJBtn;
    private javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JButton newJBtn;
    private model.PlayList playList1;
    private javax.swing.JButton saveJBtn;
    private javax.persistence.Query songQuery;
    private java.util.List<model.Song> songsInList;
    private controller.TimeRenderer timeRenderer1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    EntityManager em;
    PlayList currentlist;
    Song newSong;
    JFrame thisFrame;
    private static final long MIN_DURATION = 1800;

    
    

    //pat3group: notify listener
    private void submit(boolean exitAndSave) {
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED, exitAndSave);
        for (WindowListener wl : this.getWindowListeners()) {
            wl.windowClosed(we);
        }
        this.setVisible(false); //Hide Form
    }
}
